package com.example.prolyric;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.prolyric.database.DatabaseOffice;
import com.example.prolyric.database.JSONParser;
import com.example.prolyric.database.LyricDTO;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class LoadLyric extends LinearLayout{
	private Context mcontext;
	private TextView tv_lyric;
	private ProgressBar progress;
	private static final String URL_GET_BY_NAME = "http://10.0.2.2/Prolyric/get_lyric_by_name.php";
	private static final String xpath[] = {"//*[@class='bg_detail']/div","//*[@id='txtEnglish']"};
	private LyricDTO lyricloaded = null;
	private DatabaseOffice data ;
	
	//Budle extras =getIntent.getextras(); String url = extrs.getStringda
	//datau yv la file giao dien
//khong phai inten de tau xu li

	public LoadLyric(Context context,final AttributeSet attrSet) {
		super(context,attrSet); 
		mcontext = context;
		data = new DatabaseOffice(mcontext);
		
		//JSONParser jsonParser = new JSONParser();
		// TODO Auto-generated constructor stub
	}
	
	/*
	 * sau khi tim kiem o database, host, loidich, neu tim duoc se luu vao thuoc tinh lyricload cua lop
	 * tra ve null neu khong tim thay
	 * */
	public LyricDTO getLyricLoaded()
	{
		return this.lyricloaded;
	}

	
	
	 
	public void getLyricBySongname(Context context,String songname)
	{
		mcontext = context;
		tv_lyric = new TextView(mcontext);
		tv_lyric.setText("");
		tv_lyric.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		progress = new ProgressBar(mcontext);
		progress.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		//progress.set
		addView(tv_lyric);
		addView(progress);
		
		//bat dau tim kiem loi bai hat
		//tim kiem tren database
		this.lyricloaded = data.getLyricByName(songname);
		if(lyricloaded != null)
		{
			progress.setVisibility(View.GONE);
			tv_lyric.setVisibility(View.VISIBLE);
			tv_lyric.setText(lyricloaded.getLyricEn());
		}
		
		else 
		{
			//bat dau tim kiem tren host va tren loidich.com;
			new GetLyricFromHost().execute(songname);
		}
		
	}
	
	 
	
	/*
	 * Lay lyric tu host, truyen vao ten cua bai hat
	 * truy van, tra ve (neu co) doi tuong LYricDTO
	 * */
	private class GetLyricFromHost extends AsyncTask<String, Integer, LyricDTO>
	{

		@Override
		protected void onPostExecute(LyricDTO result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			LoadLyric.this.lyricloaded = result;
			if(result != null)
			{
				progress.setVisibility(View.GONE);
				tv_lyric.setVisibility(View.VISIBLE);
				tv_lyric.setText(result.getLyricEn().replaceAll("<br />", ""));
				  result.getStandarLyric();

				//luu lyric tim duoc vao database
				data.insertLyric(result);
			}
			else 
			{
				//cho nay tiep tuc tim tren loidich.com
				progress.setVisibility(View.GONE);
				tv_lyric.setVisibility(View.VISIBLE);
				tv_lyric.setText("Can't load from host");
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress.setVisibility(View.VISIBLE);
			tv_lyric.setVisibility(View.GONE);
		}

		@Override
		protected LyricDTO doInBackground(String... params) {
			
			LyricDTO result = null;
			
			
			List<NameValuePair> listparam = new ArrayList<NameValuePair>();
			listparam.add(new BasicNameValuePair("songname", params[0]));
			JSONParser jsonParser = new JSONParser();
			int success;
			// TODO Auto-generated method stub
             // getting product details by making HTTP request
             // Note that product details url will use GET request
			try
			{
             JSONObject json = jsonParser.makeHttpRequest(URL_GET_BY_NAME, "POST", listparam);
             if(json==null)
            	 Log.d("get lyric from host", "json is null");
            	
             else{
            	 Log.d("get lyric from host", json.toString());
             
             // json success tag
             success = json.getInt("success");
             if (success == 1) {
            	 result = new LyricDTO();
                 // successfully received product details 
                 JSONArray lyricObject = json .getJSONArray("lyric"); // JSON Array

                 // get first product object from JSON Array
                 JSONObject lyric = lyricObject.getJSONObject(0);
                 result.setSongName(lyric.getString("songname"));
                 result.setSinger(lyric.getString("singer"));
                 result.setLyricEn(lyric.getString("lyricEn"));
                 result.setLyricVi(lyric.getString("lyricVi"));
                 result.setLink(lyric.getString("link")); 
               
                 // product with this pid found
                 // Edit Text
                

             }else{
                 // product with pid not found
             }
			}
         } catch (JSONException e) {
             e.printStackTrace();
         }
   


				return result;

		
	}
	}
	
	
	
	
	/*
	 * neu tim lyric o database va o host khong co se tiep tuc tim o trang web loidich.com
	 * viec tim kiem dua vao xpath va ten link bai hat
	 * 
	 * */
	private class DowloadLyric extends AsyncTask<String, Integer, String[]>
	{

		@Override
		protected void onPostExecute(String[] result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.setVisibility(View.GONE);
			tv_lyric.setVisibility(View.VISIBLE);
			tv_lyric.setText(result[0]);
			
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress.setVisibility(View.VISIBLE);
			tv_lyric.setVisibility(View.GONE);
			
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		//param truyen vao la 1 mang 2 ohan tu chua xpath cua en va vn
		@Override
		protected String[] doInBackground(String... params) {
			String []result = new String[2];
			/*int n=params.length;
			for(int i=0;i<n;i++)
			{
				result[i] = getLyricFromURl(url, params[i]);
			}
			*/
			
			
			try {
				result[0] = getLyricFromURl(params[0], xpath[0]);
				result[1] = getLyricFromURl(params[0], xpath[1]);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result[0] = "Can't load lyric !!!";
				result[1] = "Can't load lyric !!!";
			}
			return result;
		}
		
	}
	
	
	
	public String getLyricFromURl(String songURL,String xpath) throws Exception {
		String stats="";
		
		// cau hinh thuoc tinh cleaner
		HtmlCleaner htmlCleaner = new HtmlCleaner();
		CleanerProperties props = htmlCleaner.getProperties();
		props.setAllowHtmlInsideAttributes(false);
		props.setAllowMultiWordAttributes(true);
		props.setRecognizeUnicodeChars(true);
		props.setOmitComments(true);
		
		//cretae url object
		URL url = new URL(songURL);
		//get html page root node
		TagNode root = htmlCleaner.clean(url);
		//query xpath
		Object[] statsNode = root.evaluateXPath(xpath);
		if(statsNode.length>0) {
			//do chi co 1 nen chon cai dau tien
			TagNode resultNode = (TagNode)statsNode[0];
			stats = resultNode.getText().toString();
			//Log.i("blah", stats);
			
			//stats = stats.replaceAll("[^\\p{Alpha},s]+","");
			//stats.replace("AA","\n");
		}
		
		return stats;
	}
	
	}

